package com.example.night.service.MysqlService;

import com.example.night.data.InfluencerCoins.InfluencerCoins;
import com.example.night.data.InfluencerCoins.InfluencerCoinsRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

@Slf4j
@Service
public class InfluencerCoinsMysqlService {

    private final InfluencerCoinsRepository influencerCoinsRepository;

    @Autowired
    public InfluencerCoinsMysqlService(InfluencerCoinsRepository influencerCoinsRepository) {
        this.influencerCoinsRepository = influencerCoinsRepository;
    }

    public InfluencerCoins addOrUpdateInfluencerCoins(InfluencerCoins influencerCoins) {
        try {
            Optional<InfluencerCoins> existingRecord = influencerCoinsRepository.findByPromoteId(influencerCoins.getPromoteId());

            if (existingRecord.isPresent()) {
                // 存在，更新信息
                InfluencerCoins existing = existingRecord.get();
                existing.setPromoteName(influencerCoins.getPromoteName());
                existing.setPhone(influencerCoins.getPhone());
                existing.setName(influencerCoins.getName());
                existing.setCoins(influencerCoins.getCoins());
                existing.setWithdrawnCoins(influencerCoins.getWithdrawnCoins());
                existing.setPendingWithdrawCoins(influencerCoins.getPendingWithdrawCoins());

                InfluencerCoins updated = influencerCoinsRepository.save(existing);
                log.info("达人金币信息已更新：{}", updated);
                return updated;
            } else {
                // 不存在，新增
                InfluencerCoins saved = influencerCoinsRepository.save(influencerCoins);
                log.info("新增达人金币信息成功：{}", saved);
                return saved;
            }
        } catch (Exception e) {
            log.error("新增或更新达人金币信息失败", e);
            return null;
        }
    }
    /**
     * 新增达人金币信息
     */
    public List<InfluencerCoins> addOrUpdateInfluencerCoinsBatch(List<InfluencerCoins> influencerCoinsList) {
        try {
            // 提取所有 promoteId
            List<String> promoteIds = influencerCoinsList.stream()
                    .map(InfluencerCoins::getPromoteId)
                    .toList();

            // 一次性查询所有已存在的记录，减少数据库查询次数
            List<InfluencerCoins> existingRecords = influencerCoinsRepository.findByPromoteIdIn(promoteIds);

            // 将已存在的记录转换为 Map 结构，便于快速查找
            Map<String, InfluencerCoins> existingRecordsMap = existingRecords.stream()
                    .collect(Collectors.toMap(InfluencerCoins::getPromoteId, record -> record));

            List<InfluencerCoins> recordsToSave = new ArrayList<>();

            for (InfluencerCoins influencerCoins : influencerCoinsList) {
                if (existingRecordsMap.containsKey(influencerCoins.getPromoteId())) {
                    // **已存在，更新数据**
                    InfluencerCoins existing = existingRecordsMap.get(influencerCoins.getPromoteId());
                    existing.setPromoteName(influencerCoins.getPromoteName());
                    existing.setPhone(influencerCoins.getPhone());
                    existing.setName(influencerCoins.getName());
                    existing.setCoins(influencerCoins.getCoins());
                    existing.setWithdrawnCoins(influencerCoins.getWithdrawnCoins());
                    existing.setPendingWithdrawCoins(influencerCoins.getPendingWithdrawCoins());

                    recordsToSave.add(existing);
                } else {
                    // **不存在，新增数据**
                    recordsToSave.add(influencerCoins);
                }
            }

            // **批量保存（新增或更新）**
            List<InfluencerCoins> savedRecords = influencerCoinsRepository.saveAll(recordsToSave);
            log.info("批量新增/更新达人金币信息成功，处理 {} 条记录", savedRecords.size());
            return savedRecords;

        } catch (Exception e) {
            log.error("批量新增或更新达人金币信息失败", e);
            return List.of();
        }
    }


    /**
     * 根据抖音 ID 查询达人信息
     */
    public Optional<InfluencerCoins> getByPromoteId(String promoteId) {
        try {
            return influencerCoinsRepository.findByPromoteId(promoteId);
        } catch (Exception e) {
            log.error("根据抖音 ID 查询失败：{}", promoteId, e);
            return Optional.empty();
        }
    }

    /**
     * 根据抖音名查询达人信息
     */
    public Optional<InfluencerCoins> getByPromoteName(String promoteName) {
        try {
            return influencerCoinsRepository.findByPromoteName(promoteName);
        } catch (Exception e) {
            log.error("根据抖音名查询失败：{}", promoteName, e);
            return Optional.empty();
        }
    }

    /**
     * 查询所有达人金币信息
     */
    public List<InfluencerCoins> getAll() {
        try {
            return influencerCoinsRepository.findAll();
        } catch (Exception e) {
            log.error("查询所有达人金币信息失败", e);
            return List.of();
        }
    }

    /**
     * 增加金币
     */
    @Transactional
    public boolean addCoins(String promoteId, int additionalCoins) {
        try {
            int result = influencerCoinsRepository.updateCoins(promoteId, additionalCoins);
            if (result > 0) {
                log.info("增加金币成功：promoteId={}，增加金币={}", promoteId, additionalCoins);
                return true;
            }
            log.warn("增加金币失败：promoteId={}", promoteId);
            return false;
        } catch (Exception e) {
            log.error("增加金币时发生异常", e);
            return false;
        }
    }

    /**
     * 提现金币
     */
    @Transactional
    public boolean withdrawCoins(String promoteId, int coinsToWithdraw) {
        try {
            int result = influencerCoinsRepository.withdrawCoins(promoteId, coinsToWithdraw);
            if (result > 0) {
                log.info("提现金币成功：promoteId={}，提现金币={}", promoteId, coinsToWithdraw);
                return true;
            }
            log.warn("提现金币失败：promoteId={}，提现金币={}", promoteId, coinsToWithdraw);
            return false;
        } catch (Exception e) {
            log.error("提现金币时发生异常", e);
            return false;
        }
    }

    /**
     * 根据 promoteId 更新部分信息（抖音名、电话、真实姓名）
     */
    @Transactional
    public boolean updateInfluencerInfo(String promoteId, String promoteName, String phone, String name) {
        try {
            int result = influencerCoinsRepository.updateInfluencerInfo(promoteId, promoteName, phone, name);
            if (result > 0) {
                log.info("更新达人信息成功：promoteId={}", promoteId);
                return true;
            }
            log.warn("更新达人信息失败：promoteId={}", promoteId);
            return false;
        } catch (Exception e) {
            log.error("更新达人信息时发生异常", e);
            return false;
        }
    }

    /**
     * 根据 promoteId 更新所有信息
     */
    @Transactional
    public boolean updateAllInfluencerInfo(String promoteId, String promoteName, String phone, String name, int coins, int withdrawnCoins, int pendingWithdrawCoins) {
        try {
            int result = influencerCoinsRepository.updateAllInfluencerInfo(promoteId, promoteName, phone, name, coins, withdrawnCoins, pendingWithdrawCoins);
            if (result > 0) {
                log.info("更新达人所有信息成功：promoteId={}", promoteId);
                return true;
            }
            log.warn("更新达人所有信息失败：promoteId={}", promoteId);
            return false;
        } catch (Exception e) {
            log.error("更新达人所有信息时发生异常", e);
            return false;
        }
    }

    /**
     * 根据 promoteId 修改 promoteId
     */
    @Transactional
    public boolean updatePromoteId(String oldPromoteId, String newPromoteId) {
        try {
            int result = influencerCoinsRepository.updatePromoteId(oldPromoteId, newPromoteId);
            if (result > 0) {
                log.info("更新 promoteId 成功：{} -> {}", oldPromoteId, newPromoteId);
                return true;
            }
            log.warn("更新 promoteId 失败：{} -> {}", oldPromoteId, newPromoteId);
            return false;
        } catch (Exception e) {
            log.error("更新 promoteId 时发生异常", e);
            return false;
        }
    }

    /**
     * 删除达人金币信息
     */
    @Transactional
    public boolean deleteByPromoteId(String promoteId) {
        try {
            Optional<InfluencerCoins> optional = influencerCoinsRepository.findByPromoteId(promoteId);
            if (optional.isPresent()) {
                influencerCoinsRepository.delete(optional.get());
                log.info("删除达人金币信息成功：promoteId={}", promoteId);
                return true;
            }
            log.warn("删除达人金币信息失败：promoteId={}", promoteId);
            return false;
        } catch (Exception e) {
            log.error("删除达人金币信息时发生异常", e);
            return false;
        }
    }
}
